package com.rxb.blog.service.impl;

import com.rxb.blog.entity.UserEntity;
import com.rxb.blog.mapper.UserMapper;
import com.rxb.blog.service.UserService;
import com.rxb.blog.utils.BlogException;
import com.rxb.blog.utils.EmailUtil;
import com.rxb.blog.utils.IpUtil;
import com.rxb.blog.utils.MD5Util;
import com.rxb.blog.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author：rxb
 * Date：2020-01-16 16:50
 * Description：<描述>
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmailUtil emailUtil;

    Map identifyCodeMap = new ConcurrentHashMap<String,String>();

    @Override
    public UserEntity selectById(int id){
        return userMapper.selectById(id);
    }

    @Override
    public void login(UserVo userVo, HttpServletRequest request) throws BlogException {
        userVo.setPassword(MD5Util.encode(userVo.getPassword()));

        UserEntity user=  userMapper.selectByUsername(userVo);
        if(null == user){
            throw new BlogException("当前用户不存在");
        }else if(!userVo.getPassword().equals(user.getPassword())){
            throw new BlogException("密码错误");
        }

        //更新当前用户登录ip地址
        String ip = IpUtil.getIpAddress(request);
        userVo.setIp(ip);
        userMapper.updateUser(userVo);
    }

    @Override
    public String register(UserVo userVo) throws BlogException {
        userVo.setPassword(MD5Util.encode(userVo.getPassword()));

        UserEntity user=  userMapper.selectByUsername(userVo);
        if(null != user){
            throw new BlogException("当前用户已存在，请不要重复注册");
        }
        // email作为找回密码的凭证，在库中要唯一
        UserEntity userInfoByEmail =  userMapper.selectByEmail(userVo);
        if(null != userInfoByEmail){
            throw new BlogException("当前邮箱已存在，请换一个邮箱");
        }

        userMapper.insertUser(userVo);
        return "注册成功";
    }

    @Override
    public void sendIdentifyCode(UserVo userVo) throws IOException, MessagingException, BlogException {
        //查找当前用户是否与当前邮箱匹配（这边做一对一处理  ）
        UserEntity userEntity = userMapper.selectByUsernameAndEmail(userVo);
        if(null != userEntity){
            long randomNum = Math.round((Math.random() + 1) * 1000); //随机生成四位验证码
            emailUtil.sendEmail("验证码", "您的验证码：<a>"+String.valueOf(randomNum)+"</a>,请不要泄露", userVo.getEmail());

            identifyCodeMap.put("identifyCode",String.valueOf(randomNum));
        }else{
            throw new BlogException("姓名或邮箱不正确");
        }
    }

    @Override
    public void findPassword(UserVo userVo) throws IOException, MessagingException, BlogException {
        if(userVo.getIdentifyCode().equals(identifyCodeMap.get("identifyCode"))){
            UserEntity userEntity = userMapper.selectByUsernameAndEmail(userVo);
            if(null != userEntity){
                emailUtil.sendEmail("密码", "您的密码：<a>"+userEntity.getPassword()+"</a>,请不要泄露", userVo.getEmail());
            }else{
                throw new BlogException("姓名或邮箱不正确");
            }
        }else{
            throw new BlogException("验证码错误,请重新点击发送验证码");
        }
        identifyCodeMap.clear();
    }

    @Override
    public Map getUsers(int currentPage, int pageSize) {
        Map map = new HashMap();
        List<UserEntity> users = userMapper.getUsers((currentPage-1)*pageSize,pageSize);
        users.forEach(u -> u.setUserFlag(false)); // 1 没有实际意义，用于页面 "多选"用
        int usersTotalNum = userMapper.getUsersTotalNum();
        map.put("userList",users);
        map.put("usersTotalNum",usersTotalNum);
        return  map;
    }

    @Override
    public void updateUser(UserVo userVo) {
        userMapper.updateUserById(userVo);
    }

    @Override
    public void deleteUser(UserVo userVo) {
        userMapper.deleteUser(userVo);
    }

    @Override
    public void addUser(UserVo userVo) throws BlogException {
        UserEntity user=  userMapper.selectByUsername(userVo);
        if(null != user){
            throw new BlogException("当前用户已存在，请不要重复插入");
        }
        // email作为找回密码的凭证，在库中要唯一
        UserEntity userInfoByEmail =  userMapper.selectByEmail(userVo);
        if(null != userInfoByEmail){
            throw new BlogException("当前邮箱已存在，请换一个邮箱");
        }
        userMapper.insertUser(userVo);
    }

    @Override
    public void deleteUsers(List<Integer> ids) {
        userMapper.deleteUsers(ids);
    }


}
